<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb>
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card shadow="always" :body-style="{ padding: '20px' }">
      <el-row :gutter="20">
        <el-col :span="12" :offset="0">
          <el-button type="primary" size="default" @click="addRole">
            添加角色
          </el-button>
        </el-col>
      </el-row>
      <!-- 角色列表 -->
      <el-table :data="roleList" border stripe>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <div>
              <el-row
                v-for="(item1, i1) in scope.row.children"
                :class="[i1 == 0 ? 'bdtop' : '', 'bdbottom', 'vcenter']"
                :key="item1.id"
              >
                <!-- NO1 -->
                <el-col :span="5" :offset="0">
                  <el-tag
                    size="normal"
                    effect="light"
                    closable
                    @close="removeRightById(scope.row, item1.id)"
                  >
                    {{ item1.authName }}
                  </el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <el-col :span="19" :offset="0">
                  <el-row
                    v-for="(item2, i2) in item1.children"
                    :key="item2.id"
                    :class="[i2 == 0 ? '' : 'bdtop', 'vcenter']"
                  >
                    <!-- NO2 -->
                    <el-col :span="6" :offset="0">
                      <el-tag
                        type="success"
                        size="normal"
                        effect="light"
                        closable
                        @close="removeRightById(scope.row, item2.id)"
                      >
                        {{ item2.authName }}
                      </el-tag>
                      <i class="el-icon-caret-right"></i>
                    </el-col>
                    <!-- NO3 -->
                    <el-col :span="18" :offset="0">
                      <el-tag
                        v-for="item3 in item2.children"
                        :key="item3.id"
                        type="warning"
                        size="normal"
                        effect="light"
                        closable
                        @close="removeRightById(scope.row, item3.id)"
                      >
                        {{ item3.authName }}
                      </el-tag>
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
            </div>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"> </el-table-column>
        <el-table-column prop="roleName" label="角色"> </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
        <el-table-column label="操作" width="300">
          <template slot-scope="scope">
            <div>
              <el-button type="primary" size="mini" icon="el-icon-edit">
                编辑
              </el-button>
              <el-button
                type="danger"
                size="mini"
                icon="el-icon-delete"
                @click="removeRole(scope.id)"
              >
                删除
              </el-button>
              <el-button
                type="warning"
                size="mini"
                icon="el-icon-setting"
                @click="showSetRightDialog(scope.row)"
              >
                分配权限
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!-- card body -->
    </el-card>
    <!-- 分配权限dialog -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="50%"
      @close="setRightDialogClosed"
    >
      <el-tree
        ref="treeRef"
        :data="rightList"
        node-key="id"
        :props="treeProps"
        empty-text=""
        show-checkbox
        default-expand-all="true"
        highlight-current="true"
        :default-checked-keys="defKeys"
      >
      </el-tree>

      <span slot="footer">
        <el-button @click="setRightDialogVisible = false">Cancel</el-button>
        <el-button type="primary" @click="allotRights">确认</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      roleList: [],
      setRightDialogVisible: false,
      rightList: [],
      // 树形控件树形对象
      treeProps: { children: 'children', label: 'authName' },
      defKeys: [],
      roleId: ''
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    addRoles() {},
    async getRoleList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.roleList = res.data
    },
    removeRole(roleInfo) {},
    removeRightById(role, id) {
      this.$confirm('此操作将永久删除此项, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(
            `roles/${role.id}/rights/${id}`
          )
          if (res.meta.status !== 200) {
            return this.$message({
              type: 'error',
              message: '删除权限失败!'
            })
          }
          // 将返回数据直接设置给数据
          role.children = res.data
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 展示分配权限的对话框
    async showSetRightDialog(role) {
      this.roleId = role.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限列表失败')
      }
      this.rightList = res.data

      this.getLeafKeys(role, this.defKeys)
      this.setRightDialogVisible = true
    },
    getLeafKeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getLeafKeys(item, arr)
      })
    },
    setRightDialogClosed() {
      this.defKeys = []
    },
    async allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const idStrw = keys.join(',')
      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        { rids: idStrw }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('更新失败')
      }
      this.$message.success('更新成功')
      this.getRoleList()
      this.setRightDialogVisible = false
    }
  }
}
</script>
<style lang="less">
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}

.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
